/*
 * Copyright (c) 2021 Talkweb Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "beep_demo.h"

void BeepInit(void)
{
    IoTGpioInit(IOT_GPIO_IO_GPIO_9); 
    IoTIoSetFunc(IOT_GPIO_IO_GPIO_9, IOT_IO_FUNC_GPIO_9_PWM0_OUT);
    IoTGpioSetDir(IOT_GPIO_IO_GPIO_9, IOT_GPIO_DIR_OUT);
    IoTPwmInit(IOT_PWM_PORT_PWM0);
}

static void BeepStart(void)
{
    IoTPwmStart(IOT_PWM_PORT_PWM0, 50, 4000);
}

static void BeepStop(void)
{
    IoTPwmStop(IOT_PWM_PORT_PWM0);
}

void BeepCtrl(struct BEEPCTRLATTR* ctrlAttr)
{
    static unsigned char step = 0; 
    static unsigned int onceOpenCnt = 0, onceCloseCnt = 0;

    if(ctrlAttr->times <= 0)
    {
        step = 0;
        return;
    }

    if(step == 0)
    {
        onceOpenCnt = (ctrlAttr->duty*ctrlAttr->period)/ctrlAttr->callTime;
        onceCloseCnt= ((1-ctrlAttr->duty)*ctrlAttr->period)/ctrlAttr->callTime;
        BeepStart();
        step++;
    }

    else if(step == 1)
    {
        if(--onceOpenCnt <= 0)
        {
            BeepStop();
            step++;
        }
    }

    else if(step == 2)
    {
        if(--onceCloseCnt <= 0)
        {
            ctrlAttr->times--;
            step = 0;
        }
    }
}
